package com.example.oppo

import android.os.Environment
import java.io.*
import java.net.HttpURLConnection
import java.net.URL

/*public final class ZkTask {
}*/
class ZkTask(val taskinfo: TaskInfo, val zkTaskListenser: ZkTaskListenser) :
    ZkTaskController, Runnable, Comparable<ZkTask> {

    companion object {
        //保存zip问价夹
        val zipFileDir = File(Environment.getDownloadCacheDirectory().path + "zkVideoZipCache")

        //保存zip问价夹
        val unZipFileDir = File(Environment.getDownloadCacheDirectory().path + "zkVideoUnZipCache")
    }

    private lateinit var url: URL
    private lateinit var conn: HttpURLConnection
    private lateinit var inputStream: InputStream
    private lateinit var randomAccessFile: RandomAccessFile
    private var len:Int = 0

    override var puaseTask: Boolean
        get() = false
        set(value) {
            value
        }

    override fun onPause() {
        puaseTask = true;
    }

    override fun onResume() {
        puaseTask = false
        ZkPreLoadManager.instance.resumeZkTask(this);
    }

    override fun onDestroy() {
        puaseTask = true;
        //ToDo 删除缓存
        this.taskinfo.zipPath;
    }


    override fun run() {
        try {
            url = URL(taskinfo.httpUrl)
            conn = url.openConnection() as HttpURLConnection
            conn.requestMethod = "GET"
            conn.readTimeout = 3000
            val filelength = conn.contentLength
          //  conn.setRequestProperty("Range", "bytes=" +taskinfo.fromLength + "-")
            conn.connect()
            inputStream = conn.inputStream
            val dis = DataInputStream(inputStream)
            if(conn.responseCode == HttpURLConnection.HTTP_OK /*|| conn.responseCode == HttpURLConnection.HTTP_PARTIAL*/){

                randomAccessFile.seek(taskinfo.fromLength)
                val byte = ByteArray(4*1024)

                while(dis.read(byte).apply { len = this } != -1){
                   randomAccessFile.write(byte,0,len)

                    if(puaseTask){
                        return;
                    }
                }


            }
        } catch (io: IOException) {

        }


    }

    interface ZkTaskListenser {

        /**
         * 从tasklist中移除
         */
        fun onSuccess(httpUrl: String)

        /**
         * 从taskList中移除
         * 并且删除zipPath（断点续传则保留），如果有unzipPath则只删除unzipPath
         * 保险可以都删掉。。。
         */
        fun onFail(httpUrl: String)

        //fun onProgress(progress:Int)

    }

    override fun compareTo(other: ZkTask): Int {
        if (taskinfo.priority > other.taskinfo.priority) {
            return -1
        }
        if (taskinfo.priority < other.taskinfo.priority) {
            return 1
        }
        return 0
    }


}